//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    /// <summary>
    /// Custom property of a worksheet
    /// </summary>
    public class CustomProperty: IOfficeXmlSerializable
    {
        internal CustomProperty()
        {
            
        }
        public CustomProperty(string name, byte[] data)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            if (data == null)
                throw new ArgumentNullException("data");
            this.Name = name;
            this.Data = data;
        }
        #region IOfficeXmlSerializable Members

        internal const string xmlName = "customPr";

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                Contract.Requires(value != null);
                _name = value;
            }
        }

        private byte[] _data;

       

        public byte[] Data
        {
            get { return _data; }
            set
            {
                Contract.Requires(value != null);
                _data = value;
            }
        }

        void IOfficeXmlSerializable.ReadXml(ReadContext context)
        {
            using (var c = context.Read(xmlName))
            {

                Name = c.GetString("name");
                string id = c.GetString(OfficeConstants.RelationshipNamespace + "id");
                using (Stream stream = c.OpenRelatedStream(id))
                {
                    Data = new byte[stream.Length];
                    stream.Read(Data, 0, Data.Length);
                }
            }

        }

        void IOfficeXmlSerializable.WriteXml(WriteContext context)
        {
            using (var c = context.Write(xmlName))
            {

                c.SetString("name", Name);
                string id ;
                using (Stream stream = c.CreateRelatedStream("CustomProperty{0}.bin", @"application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty", @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customProperty", out id))
                {
                    stream.Write(Data, 0, Data.Length);
                    c.SetString(OfficeConstants.RelationshipNamespace + "id", id);
                }
            }
        }

        #endregion
    }
}
